package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private DishService dishService;
    /**
     * 新增套餐
     * SetmealDto = setmeal + List<SetmealDish>
     */
    @PostMapping
    @CacheEvict(cacheNames = "dish",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto){
        setmealService.savaWithDish(setmealDto);

        return R.success("添加成功");
    }


    /**
     * 分页查询
     */
    //2.显示菜品,分页查询
    @GetMapping("page")
    public R<Page<SetmealDto>> page(Long page, Long pageSize, String name){

        Page<SetmealDto> pageInfo = setmealService.pageSetmealDto(page,pageSize,name);

        return R.success(pageInfo);

    }

    /**
     *批量删除套餐
     */
    @DeleteMapping
    public R deleteByIds(Long[] ids){
        //批量删除
        //要求1：套餐正在售卖不可删除
        //要求2：删除套餐的同时（setmeal)还要删除关联的数据(setmeal_dish)
        setmealService.deleteByIds(ids);

        return R.success("删除成功");
    }

    /**
     * 启用，停用
     */
    @PostMapping("status/{status}")
    public R<String> updateStatus(@PathVariable Integer status, Long[] ids) {
        //批量修改状态
        // update dish set status=? where id in ( ids )
        setmealService.lambdaUpdate()
            .set(Setmeal::getStatus, status) //修改值
            .in(Setmeal::getId, ids)       //条件部分
            .update();                  //更新操作
        return R.success("修改成功");
    }

    /**
     * 根据分类查询套餐
     */
    @GetMapping("list")
    @Cacheable(cacheNames = "dish",key = "#categoryId + '_'",unless = "#result.data.size()<=0")
    public R<List<Setmeal>> list(Long categoryId, Integer status){
        List<Setmeal> list = setmealService.lambdaQuery()
            .eq(categoryId !=null,Setmeal::getCategoryId, categoryId)
            .eq(Setmeal::getStatus, 1)
            .list();

        return R.success(list);
    }

    /**
     * 根据Id查询套餐中的菜品信息
     * @param setmealId
     */
    @GetMapping("dish/{setmealId}")
    public R<List<DishDto>> getDishBySetmealId(@PathVariable Long setmealId){
        //select * from dish d,setmeal_dish sd where d.id = sd.id
        List<DishDto> dishList = dishService.getDishBySetmealId(setmealId);
        return R.success(dishList);
    }
}
